window.onload = function (ev) {
    this.count = 0;
};


var imgId = null;


/**
 * 系统管理--车辆管理的单例对象
 */
var car = {
    id: "carTable", //表格id
    seItem: null,		//选中的条目
    table: null,
    layerIndex: -1,
    condition: {
        carType: "",
        carColor: ""
    }
};
var x = 0; //传递数据专用
var y = 0;
var xnum = new Array(); //传递星星专用
var ynum = new Array();
var count = 0; //强制return专用

/**
 * 初始化表格的列
 */
car.initColumn = function () {
    return [
        {field: 'selectItem', radio: true},
        {
            title: '序号', field: 'number', width: 1, align: 'center', valign: 'middle', formatter: function (value, row, index) {
                return index + 1;
            }
        },
        {title: '类型', field: 'carType', align: 'center', valign: 'middle', sortable: true, formatter: function (value, row, index) {
                return '<button type="button" class="btn btn-xs btn-success" onclick="car.searchForBaidu(\''+row.carType+'\')">' + row.carType + '</button>';
        }},
        {title: '颜色', field: 'carColor', align: 'center', valign: 'middle', sortable: true},
        {title: '价格', field: 'carPrice', align: 'center', valign: 'middle', sortable: true},
        {title: '里程(km)', field: 'carMileage', align: 'center', valign: 'middle', sortable: true},
        {title: '金额(元/天)', field: 'rentMoneyOneDay', align: 'center', valign: 'middle', sortable: true},
        {title: '维修记录', field: 'modifyId', align: 'center', valign: 'middle', sortable: true, formatter: function (value, row, index) {
                if (row.modifyId === null || row.modifyId === undefined) {
                    return '无维修记录';
                } else{
                    return '<button type="button" class="btn btn-xs btn-success" onclick="car.lookModifyById(\''+row.modifyId+'\')">查看</button>';
                }
            }
        },
        {title: '罚单记录', field: 'ticketId', align: 'center', valign: 'middle', sortable: true, formatter: function (value, row, index) {
                if (row.ticketId === null || row.ticketId === undefined) {
                    return '无罚单记录';
                } else{
                    return '<button type="button" class="btn btn-xs btn-success" onclick="car.lookTicketById(\''+row.ticketId+'\')">查看</button>';
                }
            }
        },
        {title: '租赁次数', field: 'rentTimes', align: 'center', valign: 'middle', sortable: true},
        {title: '评分', field: 'carScore', align: 'center', valign: 'middle', sortable: true, formatter: function(value, row, index){
            xnum[index] = (index+1);
            ynum[index] = row.carScore;
            /*car.toStar((index+1) , row.carScore);*/
                return '<div id="carScore'+(index+1)+'" name="carScore'+(index+1)+'">' +
                            '<script>$.proxy(car.toImplementStar(xnum,ynum),window)</script>' +
                        '</div>'
            }
        },
        {title: '租赁/收藏/预约', field: 'carId', sortable: true, align: 'center', valign: 'middle', formatter: function (value, row, index) {
            return '<button type="button" class="btn btn-xs btn-success" onclick="car.toRentById(\''+ row.carId +'\')">租车</button>'
                    + '<button id=\''+ row.carId +'\' type="button" class="btn btn-xs btn-warning" onclick="car.toCollectionById(\''+ row.carId +'\')">收藏</button>'
                    + '<button id=\''+ row.carId +'\' type="button" class="btn btn-xs btn-warning" onclick="car.toOrderById(\''+ row.carId +'\')">预约</button>'
                    + '<button type="button" class="btn btn-xs btn-warning" onclick="car.seeAssess(\''+ row.carId +'\')">评价</button>'

            }}
        ];
};
/**
 * 通过name删除指定元素
 * @param name
 */
car.removeByName = function(name){
    $("div[name^='name']").remove();
}

/**
 * 显示用户评价星际
 * @param index
 * @param number
 */
car.toStar = function(index, number){
        if (number === null || number === "" || number === undefined){
            layui.use('rate', function () {
                var rate = layui.rate;
                var ins1 = rate.render({
                    elem: '#carScore'+(index)
                    , length: 5
                    , value: 3
                    , theme: '#909904'
                    , half: true
                    , text: true
                    , readonly: true
                });
            })
        } else{
            layui.use('rate', function () {
                var rate = layui.rate;
                var ins1 = rate.render({
                    elem: '#carScore'+(index)
                    , length: 5
                    , value: number
                    , theme: '#909904'
                    , half: true
                    , text: true
                    , readonly: true
                });
        })}
};

/**
 * 通过数据传递数据调星星内容
 * @param index
 * @param number
 */
car.toImplementStar = function(index, number){
    if(count !== 0){
        return;
    }
    count++;
    for (var i = 0 ; i < index.length ; i++)  {
        x = index[i];
        y = number[i];
        car.toStar(x,y);
    }
};

/**
 * 点击了查看维修记录按钮
 * @param modifyId
 */
car.lookModifyById = function(modifyId){
    if(!modifyId){
        if (!this.check()) {
            return;
        }
    }
    var selectId = modifyId;
    if (!modifyId) {
        selectId = this.seItem.modifyId;
    }
    this.layerIndex = layer.open({
        type: 2,
        title: '维修记录',
        area: ['500px', '300px'],
        fix: false,
        maxmin: true,
        content: Feng.ctxPath + '/modify/car_modify?modifyId=' + selectId
    });
};

/**
 * 站内搜索
 */
car.searchForBaidu = function(result){
    this.layerIndex = layer.open({
        type: 2,
        title: '站内搜索',
        area: ['800px', '650px'],
        fix: false,
        maxmin: true,
        content: "https://www.baidu.com/s?wd=" + result
    });
};


/**
 * 点击了查看罚单记录按钮
 * @param ticketId
 */
car.lookTicketById = function(ticketId){
    if(!ticketId){
        if (!this.check()) {
            return;
        }
    }
    var selectId = ticketId;
    if (!ticketId) {
        selectId = this.seItem.modifyId;
    }
    car.layerIndex = layer.open({
        type: 2,
        title: '罚单记录',
        area: ['500px', '300px'],
        fix: false,
        maxmin: true,
        content: Feng.ctxPath + '/ticket/car_ticket?ticketId=' + selectId
    });
};


/**
 * 检查是否选中
 */
car.check = function () {
    var selected = $('#' + this.id).bootstrapTable('getSelections');
    if (selected.length === 0) {
        Feng.info("请先选中表格中的某一记录！");
        return false;
    } else {
        car.seItem = selected[0];
        return true;
    }
};

/**
 * 点击添加
 */
car.openAddCar = function () {
    this.layerIndex = layer.open({
        type: 2,
        title: '添加车辆',
        area: ['500px', '580px'],
        fix: false,
        maxmin: true,
        content: Feng.ctxPath + '/car/car_add'
    });
};

/**
 * 点击修改按钮时
 */
car.openChangeCar = function (carId) {
    if(!carId){
        if (!this.check()) {
            return;
        }
    }
    var selectId = carId;
    if (!carId) {
        selectId = this.seItem.carId;
    }
    this.layerIndex = layer.open({
        type: 2,
        title: '编辑车辆',
        area: ['350px', '580px'],
        fix: false,
        maxmin: true,
        content: Feng.ctxPath + '/car/car_edit?carId=' + selectId
    });
};

/**
 * 点击删除按钮
 */
car.delCar = function () {
    if (this.check()) {
        var operation = function () {
            var carId = car.seItem.carId;
            var ajax = new $ax(Feng.ctxPath + "/car/delete", function () {
                Feng.success("删除成功!");
                count = 0;
                car.table.refresh();
            }, function (data) {
                Feng.error("删除失败!" + data.responseJSON.message + "!");
            });
            ajax.set("carId", carId);
            ajax.start();
        };
        Feng.confirm("是否删除车辆?", operation);
    }
};

/**
 * 通过Id删除车辆
 */
car.delCarById = function (carId) {
    var operation = function () {
        var ajax = new $ax(Feng.ctxPath + "/car/delete", function () {
            Feng.success("删除成功!");
            count = 0;
            car.table.refresh();
        }, function (data) {
            Feng.error("删除失败!" + data.responseJSON.message + "!");
        });
        ajax.set("carId", carId);
        ajax.start();
    };
    Feng.confirm("是否删除用户?", operation);
};

/**
 * 点击查询按钮
 */
car.search = function () {
    var queryData = {};

    queryData['carType'] = car.condition.carType;
    queryData['carColor'] = car.condition.carColor;
    queryData['timeLimit'] = $("#timeLimit").val();
    count = 0;
    car.table.refresh({query: queryData});
};

$(function () {

    car.app = new Vue({
        el: '#carManagerPage',
        data: car.condition
    });
    var defaultColunms = car.initColumn();
    var table = new BSTable("carTable", "/car/list", defaultColunms);
    table.setPaginationType("client");
    car.table = table.init();
    laydate.render({
        elem: '#timeLimit',
        range: true,
        theme: '#009efb',
        max: Feng.currentDate()
    });
});

/**
 * 点击租车按钮
 * @param carId
 */
car.toRentById = function (carId) {
    if(!carId){
        if (!this.check()) {
            return;
        }
    }
    var selectId = carId;
    if (!carId) {
        selectId = this.seItem.carId;
    }
    this.layerIndex = layer.open({
        type: 2,
        title: '租车中',
        area: ['800px', '500px'],
        fix: false,
        maxmin: true,
        content: Feng.ctxPath + '/car/car_rent?carId=' + selectId
    });
};
/**
 * 收藏车辆
 * @param carId
 */
car.toCollectionById = function (carId) {
    if(!carId){
        if (!this.check()) {
            return;
        }
    }
    var selectId = carId;
    if (!carId) {
        selectId = this.seItem.carId;
    }
    var ajax = new $ax(Feng.ctxPath + "/car/car_collection?carId=" + selectId, function (data) {
        window.parent.Feng.success("收藏成功!");
        $("#"+carId).text("已收藏");
        $("#"+carId).attr("disabled","disabled");
    }, function (data) {
        Feng.error("收藏失败!" + data.responseJSON.message + "!");
    });
    ajax.start();
};

/**
 * 预约车辆
 * @param carId
 */
car.toOrderById = function (carId) {
    if(!carId){
        if (!this.check()) {
            return;
        }
    }
    var selectId = carId;
    if (!carId) {
        selectId = this.seItem.carId;
    }
    var ajax = new $ax(Feng.ctxPath + "/car/car_order?carId=" + selectId, function (data) {
        window.parent.Feng.success("预约成功!");
        car.table.refresh();
    }, function (data) {
        Feng.error("预约失败!" + data.responseJSON.message + "!");
    });
    ajax.start();
};


/**
 * 跳转到我的收藏页面
 */
car.openMyCollectionCar = function () {
    this.layerIndex = layer.open({
        type: 2,
        title: '我的收藏',
        area: ['800px', '650px'],
        fix: false,
        maxmin: true,
        content: Feng.ctxPath + '/car/myCollection'
    });
};


/**
 * 跳转到我的预约页面
 */
car.openMyOrderCar = function () {
    this.layerIndex = layer.open({
        type: 2,
        title: '我的预约',
        area: ['800px', '650px'],
        fix: false,
        maxmin: true,
        content: Feng.ctxPath + '/car/myOrder'
    });
};

car.seeAssess = function (carId) {
    var selectId = carId;
    this.layerIndex = layer.open({
        type: 2,
        title: '查看评价',
        area: ['800px', '650px'],
        fix: false,
        maxmin: true,
        content: Feng.ctxPath + '/car/seeAssess?carId=' + selectId
    });
};



/*
car.uploadCarImg = function () {
    if (this.check()) {
        var carId = car.seItem.carId;
        imgId = carId;
        this.layerIndex = layer.open({
            type: 2,
            title: '查看评价',
            area: ['800px', '750px'],
            fix: false,
            maxmin: true,
            content: Feng.ctxPath + '/car/car_file'
        });
    }
};*/

car.getId = function(){
    /*$('#img').hide();*/
    car.check();
    $("#uploadImg").prop("name",car.seItem.carId);
};

//上传图片
        layui.use('upload', function(){
        var $ = layui.jquery
            ,upload = layui.upload;
        //普通图片上传
        var uploadInst = upload.render({
            elem: '#uploadImg'
            ,url: Feng.ctxPath + '/car/uploadCarImg'
            ,data:{
                carId:function () {
                    return $("#uploadImg").attr("name");
                }
            }
            /*,before: function(obj){
                //预读本地文件示例，不支持ie8
                obj.preview(function(index, file, result){
                    $('#img').show();
                    $('#img').innerHTML="<img src='"+result+"' width=\"90px\" height=\"90px\" class=\"layui-upload-img\">";
                });
            }*/
            ,done: function(res){
                //如果上传失败
                if(res.code > 200){
                    return layer.msg('上传失败');
                }
                return layer.msg('上传成功');
                //上传成功
            }
            ,error: function(){
                //演示失败状态，并实现重传
                var demoText = $('#demoText');
                demoText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-xs demo-reload">重试</a>');
                demoText.find('.demo-reload').on('click', function(){
                    uploadInst.upload();
                });
            }
        });
    });


